package prepare;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * ImplementsLRUWithLinkedHashMap
 *
 * @author <a href="zhaoyingling12@163.com">Zhao Simon</a>
 * @description: LRU 最近最少使用算法
 * @date 2021/6/2
 **/
public class ImplementsLRUWithLinkedHashMap {
    public static void main(String[] args) {
        // accessOrder = true 表示按照访问顺序进行排序，accessOrderedMap = false 表示按照插入顺序排序
        LinkedHashMap<String, String> accessOrderedMap = new LinkedHashMap<String, String>(16, 0.75F, true) {
            // 实现自定义删除策略，否则行为就和普遍Map没有区别，当size() > 3 时，触发删除
            @Override
            protected boolean removeEldestEntry(Map.Entry eldest) {
                return size() > 3;
            }
        };

        LinkedHashMap<String, String> orderMap = new LinkedHashMap<String, String>(16, 0.75f, true) {
            @Override
            protected boolean removeEldestEntry(Map.Entry eldest) {
                return size() > 3;
            }
        };

        // 放入元素
        accessOrderedMap.put("Project1", "Valhalla");
        accessOrderedMap.put("Project2", "Panama");
        accessOrderedMap.put("Project3", "Loom");
        System.out.println("-----------第一次遍历-----------");
        accessOrderedMap.forEach((k, v) -> System.out.println(k + ":" + v));

        // 模拟访问
        accessOrderedMap.get("Project3");
        accessOrderedMap.get("Project2");
        accessOrderedMap.get("Project1");
        System.out.println("-----------第二次遍历-----------");
        accessOrderedMap.forEach((k, v) -> System.out.println(k + ":" + v));

        accessOrderedMap.get("Project2");
        System.out.println("-----------第三次遍历-----------");
        accessOrderedMap.forEach((k, v) -> System.out.println(k + ":" + v));

        // 插入元素
        accessOrderedMap.put("Project4", "Mission Control");

        System.out.println("-----------第四次遍历-----------");
        accessOrderedMap.forEach((k, v) -> System.out.println(k + ":" + v));
    }
}


